﻿using EFFC.Frame.Net.Module.Extend.EWRA.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFFC.Extends.LinqDLR2SQL;
using EFFC.Frame.Net.Unit.DB;
using EFFC.Frame.Net.Base.Data.Base;
using EFFC.Frame.Net.Module.Extend.EWRA.Attributes.Validation;
using EFFC.Frame.Net.Base.Common;
using EFFC.Frame.Net.Base.Data;
using EFFC.Frame.Net.Module.Business.Datas;
using ICPFrameLib.Business;
using ICPFrameLib.Attributes;
using EFFC.Frame.Net.Unit.DB.Parameters;

namespace XHRPMIS.Business.v1._0
{
    public class DynamicTemplate : MyRestLogic
    {

        [EWRARoute("get", "/d_template")]
        [EWRARouteDesc("获取动态模板列表")]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息',
data:[{
    uid:'UID',
    name:'动态模板名称',
    category:'分类',
    is_lock:'是否锁定',
}]
}")]
        object Select()
        {
            SetCacheEnable(false);
            var up = DB.NewMetaUnitParameter();

            var list = (from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_TEMPLATE", "a")
                        select new
                        {
                            uid = t.UID,
                            name = t.Name,
                            category = t.Category,
                            is_lock = t.IsLock,
                        }).GetQueryList(up);
            foreach (dynamic item in list)
            {
                item.is_lock = BoolStd.IsNotBoolThen(item.is_lock);
            }

            return new
            {
                code = "success",
                msg = "",
                data = list
            };
        }
        [EWRARoute("get", "/d_template/{uid}")]
        [EWRARouteDesc("获取指定的动态模板")]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息',
data:{
    uid:'UID',
    name:'动态模板名称',
    desc:'动态模板描述'，
    category:'分类',
    is_lock:'是否锁定'，
    settings:'动态模板的相关设定，JSON格式',
}
}")]
        object Select(string uid)
        {
            SetCacheEnable(false);
            var up = DB.NewMetaUnitParameter();

            var list = (from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_TEMPLATE", "a")
                        where t.UID == uid
                        select new
                        {
                            uid = t.UID,
                            name = t.Name,
                            desc = t.Desc,
                            category = t.Category,
                            is_lock = t.IsLock,
                            settings = t.SettingsJson,
                        }).GetQueryList(up);
            if (list.Count <= 0)
            {
                return new
                {
                    code = "failed",
                    msg = "指定的模板不存在"
                };
            }
            dynamic info = list.First();

            info.is_lock = BoolStd.IsNotBoolThen(info.is_lock);

            return new
            {
                code = "success",
                msg = "",
                data = info
            };
        }
        
        [EWRARoute("post", "/d_template")]
        [EWRARouteDesc("新增一个动态模板")]
        [EWRAEmptyValid("name")]
        [EWRAAddInput("name", "string", "名称", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAAddInput("desc", "string", "描述", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("category", "string", "分类", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("settings", "string", "设定参数，JSON格式的字符串", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息',
uid:'新增成功后返回的UID'
}")]
        object Add()
        {
            var up = DB.NewMetaUnitParameter();
            var name = ComFunc.nvl(PostDataD.name);
            var desc = ComFunc.nvl(PostDataD.desc);
            var settings = ComFunc.nvl(PostDataD.settings);
            var category = ComFunc.nvl(PostDataD.category);

            if ((from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_TEMPLATE", "a")
                 where t.Name == name
                 select t).IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "同名模板已经存在"
                };
            }
            var uid = Guid.NewGuid().ToString();
            DB.QuickInsert(up, "EXTEND_DYNAMIC_TEMPLATE", new
            {
                UID = uid,
                Name = name,
                Desc = desc,
                Category = category,
                IsLock = 0,
                SettingsJson = settings,
                add_id = TokenPayLoad.ID,
                add_ip = ClientInfo.IP,
                add_name = ComFunc.nvl(TokenPayLoad["username"]),
                add_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                last_id = TokenPayLoad.ID,
                last_ip = ClientInfo.IP,
                last_name = ComFunc.nvl(TokenPayLoad["username"]),
                last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            });

            return new
            {
                code = "success",
                msg = "操作成功",
                uid
            };
        }
        [EWRARoute("patch", "/d_template/{uid}")]
        [EWRARouteDesc("修改一个动态模板")]
        [EWRAEmptyValid("name")]
        [EWRAAddInput("uid", "string", "uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAAddInput("name", "string", "名称", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAAddInput("desc", "string", "描述", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("category", "string", "分类", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("settings", "string", "设定参数，JSON格式的字符串", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息',
uid:'成功后返回的UID'
}")]
        object Modify(string uid)
        {
            var up = DB.NewMetaUnitParameter();
            var name = ComFunc.nvl(PostDataD.name);
            var desc = ComFunc.nvl(PostDataD.desc);
            var settings = ComFunc.nvl(PostDataD.settings);
            var category = ComFunc.nvl(PostDataD.category);

            var s = from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_TEMPLATE", "a")
                    where t.UID == uid
                    select t;


            if (!s.IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "模板不存在"
                };
            }
            dynamic info = s.GetQueryList(up).First();
            if (BoolStd.IsNotBoolThen(info.IsLock))
            {
                return new
                {
                    code = "failed",
                    msg = "模板锁定中，不可删除(删除可能会导致其它模板失效或出现异常，请谨慎操作)"
                };
            }

            if ((from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_TEMPLATE", "a")
                 where t.Name == name && t.UID != uid
                 select t).IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "同名模板已经存在"
                };
            }
            DB.QuickUpdate(up, "EXTEND_DYNAMIC_TEMPLATE", new
            {
                Name = name,
                Desc = desc,
                Category = category,
                SettingsJson = settings,
                last_id = TokenPayLoad.ID,
                last_ip = ClientInfo.IP,
                last_name = ComFunc.nvl(TokenPayLoad["username"]),
                last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            }, new
            {
                UID = uid
            });

            return new
            {
                code = "success",
                msg = "操作成功",
                uid
            };
        }
        [EWRARoute("delete", "/d_template/{uid}")]
        [EWRARouteDesc("删除一个动态模板")]
        [EWRAAddInput("uid", "string", "uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息'
}")]
        object Delete(string uid)
        {
            var up = DB.NewMetaUnitParameter();
            var s = from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_TEMPLATE", "a")
                    where t.UID == uid
                    select t;
            if (!s.IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "模板不存在"
                };
            }

            dynamic info = s.GetQueryList(up).First();
            if (BoolStd.IsNotBoolThen(info.IsLock))
            {
                return new
                {
                    code = "failed",
                    msg = "模板锁定中，不可删除(删除可能会导致其它模板失效或出现异常，请谨慎操作)"
                };
            }

            DB.QuickDelete(up, "EXTEND_DYNAMIC_TEMPLATE", new
            {
                UID = uid
            });

            return new
            {
                code = "success",
                msg = "操作成功"
            };
        }
        [ActionAuth("DynamicTemplate")]
        [EWRARoute("patch", "/d_template/{uid}/lock")]
        [EWRARouteDesc("锁定一个动态模板")]
        [EWRAAddInput("uid", "string", "uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息'
}")]
        object Active(string uid)
        {
            var up = DB.NewMetaUnitParameter();

            var s = from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_TEMPLATE", "a")
                    where t.UID == uid
                    select t;
            if (!s.IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "模板不存在"
                };
            }

            dynamic info = s.GetQueryList(up).First();
            if (BoolStd.IsNotBoolThen(info.IsLock))
            {
                return new
                {
                    code = "failed",
                    msg = "模板未锁定，无需重复操作"
                };
            }
            DB.QuickUpdate(up, "EXTEND_DYNAMIC_TEMPLATE", new
            {
                IsLock = 1,
                last_id = TokenPayLoad.ID,
                last_ip = ClientInfo.IP,
                last_name = ComFunc.nvl(TokenPayLoad["username"]),
                last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            }, new
            {
                UID = uid
            });

            return new
            {
                code = "success",
                msg = "操作成功"
            };
        }
        [EWRARoute("patch", "/d_template/{uid}/unlock")]
        [EWRARouteDesc("解锁一个动态模板")]
        [EWRAAddInput("uid", "string", "uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息'
}")]
        object Deactive(string uid)
        {
            var up = DB.NewMetaUnitParameter();

            var s = from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_TEMPLATE", "a")
                    where t.UID == uid
                    select t;
            if (!s.IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "模板不存在"
                };
            }

            dynamic info = s.GetQueryList(up).First();
            if (!BoolStd.IsNotBoolThen(info.IsLock))
            {
                return new
                {
                    code = "failed",
                    msg = "模板未锁定活，无需重复操作"
                };
            }
            DB.QuickUpdate(up, "EXTEND_DYNAMIC_TEMPLATE", new
            {
                IsLock = 0,
                last_id = TokenPayLoad.ID,
                last_ip = ClientInfo.IP,
                last_name = ComFunc.nvl(TokenPayLoad["username"]),
                last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            }, new
            {
                UID = uid
            });

            return new
            {
                code = "success",
                msg = "操作成功"
            };
        }
    }
}
